/**
 * MCP Server List Component
 * 
 * Displays all registered MCP servers with their status and actions
 */

import { useState, useEffect } from 'react';
import {
  Server,
  Trash2,
  Plus,
  RefreshCw,
  CheckCircle2,
  XCircle,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import type { McpServer } from '@/api/mcp';
import * as mcpApi from '@/api/mcp';

interface MCPServerListProps {
  onAddClick: () => void;
}

export function MCPServerList({ onAddClick }: MCPServerListProps) {
  const [servers, setServers] = useState<McpServer[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadServers = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await mcpApi.listMcpServers();
      setServers(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load servers');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadServers();
  }, []);

  const handleDelete = async (name: string) => {
    if (!confirm(`确定要删除 MCP 服务器 "${name}" 吗？`)) {
      return;
    }

    try {
      await mcpApi.unregisterMcpServer(name);
      await loadServers();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to delete server');
    }
  };

  const getServerTypeBadge = (type: string) => {
    const colors: Record<string, string> = {
      stdio: 'bg-blue-500',
      sse: 'bg-green-500',
      http: 'bg-purple-500',
      sdk: 'bg-orange-500',
    };

    return (
      <Badge className={`${colors[type] || 'bg-gray-500'} text-white`}>
        {type.toUpperCase()}
      </Badge>
    );
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <RefreshCw className="w-6 h-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold">MCP 服务器</h2>
          <p className="text-sm text-muted-foreground">
            管理 Model Context Protocol (MCP) 服务器
          </p>
        </div>
        <div className="flex gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={loadServers}
          >
            <RefreshCw className="w-4 h-4 mr-2" />
            刷新
          </Button>
          <Button
            onClick={onAddClick}
            size="sm"
          >
            <Plus className="w-4 h-4 mr-2" />
            添加服务器
          </Button>
        </div>
      </div>

      {/* Error Message */}
      {error && (
        <Card className="border-destructive">
          <CardContent className="pt-6">
            <div className="flex items-center gap-2 text-destructive">
              <XCircle className="w-4 h-4" />
              <span>{error}</span>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Server List */}
      {servers.length === 0 ? (
        <Card>
          <CardContent className="pt-6">
            <div className="text-center py-8 text-muted-foreground">
              <Server className="w-12 h-12 mx-auto mb-4 opacity-50" />
              <p>暂无 MCP 服务器</p>
              <p className="text-sm mt-2">
                点击"添加服务器"按钮来注册一个新的 MCP 服务器
              </p>
            </div>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-4">
          {servers.map((server) => (
            <Card key={server.name}>
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div className="space-y-1">
                    <div className="flex items-center gap-2">
                      <Server className="w-4 h-4" />
                      <CardTitle className="text-lg">{server.name}</CardTitle>
                      {getServerTypeBadge(server.type)}
                    </div>
                    <CardDescription>
                      {server.type === 'stdio' && server.config.command && (
                        <span className="font-mono text-xs">
                          {server.config.command}
                          {server.config.args && ` ${server.config.args.join(' ')}`}
                        </span>
                      )}
                      {(server.type === 'sse' || server.type === 'http') && server.config.url && (
                        <span className="font-mono text-xs">{server.config.url}</span>
                      )}
                      {server.type === 'sdk' && (
                        <span className="text-xs">SDK MCP Server</span>
                      )}
                    </CardDescription>
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8"
                      onClick={() => handleDelete(server.name)}
                    >
                      <Trash2 className="w-4 h-4 text-destructive" />
                    </Button>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <CheckCircle2 className="w-4 h-4 text-green-500" />
                  <span>已注册</span>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
